// tslint:disable
import { PopoverComponent } from './../coms/popover/popover.component';
import { Component, OnInit, ViewChild } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { Router } from '@angular/router';
import { FormGroup, FormControl } from '@angular/forms';

import { ComItem } from './../route/entry/com-item';
import { AppGlobalService } from "./../shared/service/app-global.service";
import { EventService } from './../shared/service/event.service';
import { HttpService } from './../shared/service/http.service';
import { TabsService } from './../shared/service/tabs.service';
import { ModalController, PopoverController } from "@ionic/angular";
import { ChooseCityComponent } from "../coms/choose-city/choose-city.component";
import { ActionSheetService } from "ng-zorro-antd-mobile";

@Component({
  selector: "app-search-history",
  templateUrl: "./search-history.page.html",
  styleUrls: ["./search-history.page.scss"]
})
export class SearchHistoryPage implements OnInit {
  titleBar: any;
  showWaterImg = false; // 是否显示水印
  isGrayBg = false; // 默认背景为灰色
  coms: ComItem[];
  footerComs: ComItem[];
  cityCode: number; // 城市code
  keyword = ""; // 搜索关键词
  oneWay = "";//searchType300 的关键词
  hasSearched = false; // 是否已经搜索
  searchArr: any = []; // 搜索历史记录数组
  tagData: any;
  searchType: any;
  subSearchType: any;// 各个tab独立存储搜索历史
  searchBtnColor = "#27282E"; // 与UI沟通只显示"#27282E" add by andrew.wen for bug-view-4191.html
  listId: any; // 搜索相应的列表用的id
  allType: any;
  subWidth: any;
  showInHeader = false;
  showKeyword = true;
  haveResult = true;
  @ViewChild('searchBar') searchBar;
  popoverLabel = '找好店';
  constructor(
    private route: ActivatedRoute,
    private router: Router,
    public appGlobalService: AppGlobalService,
    private tabService: TabsService,
    private eventService: EventService,
    private httpService: HttpService,
    private modalController: ModalController,
    public popoverController: PopoverController,
  ) {



  }

  ngOnInit() {
    const that = this;
    setTimeout(() => {
      that.searchBar.setFocus();
    }, 100);
    that.route.queryParams.subscribe(p => {
      if (p.obj) {
        const tempObj = JSON.parse(p.obj);

        // 返回进入校验searchType之后不重新请求
        if (that.tagData && tempObj && that.tagData.searchType === tempObj.searchType) {
          return;
        }else{
           // 2024.06.27 已经搜索过并且当前初始化与上一次搜索类型不一致 则标记
           that.keyword = ''; 
           that.hasSearched = false;
           that.coms = null;
        }

        that.tagData = JSON.parse(p.obj);
        if (that.tagData.link && that.tagData.link.params && that.tagData.link.params.placeholder) {
          that.tagData.placeholder = that.tagData.link.params.placeholder;
        }

        if (that.tagData.link && that.tagData.link.params && that.tagData.link.params.express_no) {
          that.keyword = that.tagData.link.params.express_no;
        }

 
        that.searchType = "searchType" + this.tagData.searchType;
        console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  	this.searchType   ', this.searchType);
        that.searchArr = JSON.parse(localStorage.getItem(this.searchType))
          ? JSON.parse(localStorage.getItem(this.searchType))
          : [];
      }
      if (p.allType) {
        that.allType = p.allType;
      }
      //  蜂喔先行请求空keyword 获取分类
      if (that.tagData.position === "bottom") {
        that.searchKeyword(that.keyword, true);
      }
      //  蜂喔户型搜索先行请求空keyword 获取分类 header
      if (that.searchType === 'searchType100') {
        that.searchKeyword(that.keyword, true);
      }
      if (p.ite && that.searchType === 'searchType300') {
        that.oneWay = " ";
        // this.keyword = p.ite;
        // this.searchKeyword(this.keyword, true);
      }

      // 2.2.19 蜂喔商户新增注册类型
      if (that.searchType === 'searchType400') {
        const updateSearchParams = 'updateSearchParams';
        if (that.eventService.eventEmit.listenerCount(updateSearchParams) > 0) {
          that.eventService.eventEmit.removeListener(updateSearchParams);
        }
        that.eventService.eventEmit.on(updateSearchParams, (res) => {
          // 修改搜索参数
          if (res && res.params) {

            if (res.params.popoverLabel) {
              this.popoverLabel = res.params.popoverLabel;
            }
            if (res.params.popoverPlaceHolderLabel) {
              this.tagData.placeholder = res.params.popoverPlaceHolderLabel;
            }

            const newKey = JSON.parse(JSON.stringify(that.tagData.link.params.key));
            if (newKey.listType !== undefined) {
              newKey.listType = res.params.listType;
            }
            if (res.params.searchParams !== undefined) {
              const newParams = {};
              const pairs = res.params.searchParams.split(',');
              pairs.forEach(pair => {
                newParams[pair] = that.keyword; // 将键值对添加到对象中  
              });
              newParams['key'] = newKey
              that.tagData.link.params = {};
              that.tagData.link.params = newParams;
              console.log('new searchParams=', that.tagData.link.params);
              that.searchKeyword(that.keyword, true);
              return;
            }
          }
        });
      }
    });

    this.addTabListener();
  }

  addTabListener() {
    if (this.eventService.eventEmit.listenerCount('searchTabListener') > 0) {
      this.eventService.eventEmit.removeListener('searchTabListener');
    }
    this.eventService.eventEmit.on('searchTabListener', (obj) => {
      this.subChange(this.coms[0].tagData.data[obj.indexTab], obj.indexTab);
    });
  }

  ionBlur() {
  }
  focusInput() {
    if (this.hasSearched) {
      this.hasSearched = false;
      this.keyword = "";
    }
  }

  searchChange(event?) {
    // console.log('msg-----》'+this.keyword);
    // if (this.keyword === "") {
    //   this.searchBtnColor = "#858894";
    // } else {
    //   this.searchBtnColor = "#27282E";
    // }
    // 与UI沟通只显示"#27282E" add by andrew.wen for bug-view-4191.html
    this.searchBtnColor = "#27282E";
    if (this.searchType === 'searchType100') {
      // 实时搜索
      this.searchKeyword(this.keyword, true);
    }
  }
  search(event?, requestPage = true) {
    if (event && event.keyCode !== 13) {
      return;
    }
    this.searchBar.getInputElement().then((input) => {
      this.keyword = input.value;
      this.keyword = this.keyword.trim();
      if (this.keyword === "") {
        return;
      }

      this.hasSearched = true;
      const len = this.searchArr.length;
      if (this.keyword !== "" && this.searchArr.indexOf(this.keyword) === -1) {
        this.searchArr.unshift(this.keyword);
        if (len >= 10) {
          this.searchArr.pop();
        }
        if (this.subSearchType) {
          localStorage.setItem(this.subSearchType, JSON.stringify(this.searchArr));
        } else {
          localStorage.setItem(this.searchType, JSON.stringify(this.searchArr));
        }

      }
      this.searchKeyword(this.keyword, requestPage);

    });


  }

  // requestPage 判断首页搜索是否每次都请求page
  searchKeyword(keyword, requestPage?) {

    console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  searchKeyword	   ', keyword);
    this.keyword = keyword;
    this.hasSearched = true;

    // 2023.11.8 检查当前是否有position有则赋值requestPage为true
    if (this.tagData.position !== undefined) {
      requestPage = true;
    }
    if (requestPage) {

      // home search
      if (this.searchType === 'searchType1' || this.searchType === 'searchType100' || this.searchType === 'searchType300' || this.searchType === 'searchType400') {
        console.log("首页搜索\n");
        const session = localStorage.getItem("sessionId");
        // 参数组合
        const search = {};
        const params = { search };
        for (const prop in this.tagData.link.params) {
          if (this.tagData.link.params.hasOwnProperty(prop)) {
            if (prop !== 'key') {
              search[prop] = keyword;
            } else {
              // tagData.link.params.key 默认参数
              for (const p in this.tagData.link.params.key) {
                if (this.tagData.link.params.key.hasOwnProperty(p)) {
                  params[p] = this.tagData.link.params.key[p];
                }
              }
            }

          }
        }
        // this.keyword = '';
        params.search = search;
        let pageParams: any;
        if (params) {
          pageParams = {
            sessionId: session,
            pageId: this.tagData.link.target,
            params
          };
        }
        this.getHomeSearchData(pageParams);

      } else if (this.searchType === 'searchType300') {

      } else {
        console.log("非首页搜索\n");
        const session = localStorage.getItem("sessionId");
        // 参数组合
        const search = {};
        const params = { search };
        for (const prop in this.tagData.partLink.params) {
          if (this.tagData.partLink.params.hasOwnProperty(prop)) {
            if (prop !== 'key') {
              search[prop] = keyword;
            } else {
              for (const p in this.tagData.partLink.params.key) {
                if (this.tagData.partLink.params.key.hasOwnProperty(p)) {
                  params[p] = this.tagData.partLink.params.key[p];
                }
              }
            }

          }
        }
        let pageParams: any;
        pageParams = {
          sessionId: session,
          viewId: this.tagData.partLink.target,
          params
        };
        this.getData(pageParams);
      }
    } else {
      // 蜂喔首页搜索走这里
      if (this.coms[0] && this.coms[0].tagData
        && this.coms[0].tagData.currentTab) {
        this.subChange(this.coms[0].tagData.data[this.coms[0].tagData.currentTab], this.coms[0].tagData.currentTab, true);
      }

    }

  }

  getData(pageParams) {
    setTimeout(() => {
      this.httpService.post('application/part', pageParams, (res: any) => {
        if (res) {
          const tmpData = JSON.parse(res.script);
          this.tabService.getPageDataWithBuffer(tmpData, callData => {
            this.coms = callData.coms;
            this.footerComs = callData.footerComs;
            this.isGrayBg = callData.isGrayBg;
          });
        }
      });
    }, 20);
  }


  getHomeSearchData(pageParams) {
    this.httpService.post('application/page', pageParams, res => {

      // 请求数据成功
      if (res) {
        this.tabService.getPageData(res, pageData => {
          for (let index = 0; index < pageData.coms.length; index++) {
            const element = pageData.coms[index];
            if (element.tagData.style === 'tag.FilterTagLogic') {
              element.tagData.search = pageParams.params.search;
              break;
            }
          }
          this.coms = pageData.coms;
          this.isGrayBg = pageData.isGrayBg;
          this.showWaterImg = pageData.showWaterImg;
          //  蜂喔赚钱宝1.7.1 新增底部按钮
          if (pageData.footerComs) {
            this.footerComs = pageData.footerComs;
          }
          if (!this.titleBar && pageData.titleBar) {
            // 设置默认带入的城市
            this.titleBar = pageData.titleBar;
            if (this.titleBar.position && this.titleBar.position.code) {
              if (this.tagData.link.params && this.tagData.link.params.key) {
                this.tagData.link.params.key.cityId = this.titleBar.position.code;
              } else if (this.tagData.link.params) {
                this.tagData.link.params.key = { cityId: this.titleBar.position.code };
              }
            }

          }
          if (this.searchType === 'searchType100' && this.keyword === '') {
            this.hasSearched = false;
            return;
          }

          if (this.coms[0] && this.coms[0].tagData.style === 'tag.AppTabTagLogic' && this.coms[0].tagData.name === 'imagesTag') {
            // 加参数
            if (this.coms[0].tagData.ifsearch) {
              const dataLen = this.coms[0].tagData.data.length;
              for (let j = 0; j < dataLen; j++) {
                const k = this.coms[0].tagData.data[j];
                k.partLink.params.search = this.tagData.link.params;
                console.log('set params to partlink>', this.coms[0].tagData.data[j]);
              }
            }

            this.showInHeader = true;
            if (this.coms[0].tagData.currentData
              && this.coms[0].tagData.currentData.tags.length > 0
              && this.coms[0].tagData.currentData.tags[0]
              && this.coms[0].tagData.currentData.tags[0].name === 'switchBlockTag'
            ) {
              this.showInHeader = false;
            }
            this.subWidth = 100 / this.coms[0].tagData.data.length + '%';

            if (this.tagData.link.params.key && this.tagData.link.params.key.indexTab >= 0) {
              // 蜂喔首页搜索设置默认选中tab
              this.coms[0].tagData.currentTab = this.tagData.link.params.key.indexTab
              this.subChange(this.coms[0].tagData.data[this.coms[0].tagData.currentTab], this.coms[0].tagData.currentTab, true);
            } else {
              // 设置默认tab0 的历史记录
              if (this.coms[0].tagData.data[0].partLink && this.coms[0].tagData.data[0].partLink.params && this.coms[0].tagData.data[0].partLink.params.subSearchType) {
                this.subSearchType = this.coms[0].tagData.data[0].partLink.params.subSearchType;
                this.subSearchHistroy();
              }

            }

            if (
              this.coms[0].tagData.currentData
              && this.coms[0].tagData.currentData.tags.length > 0
              && this.coms[0].tagData.currentData.tags[1]
              && this.coms[0].tagData.currentData.tags[1].data
              && this.coms[0].tagData.currentData.tags[1].data.data
              && this.coms[0].tagData.currentData.tags[1].data.data.length > 0
            ) {
              this.showKeyword = false;
            } else {
              this.showKeyword = true;
            }

            // 蜂喔 首次page不展示空key搜索结果
            if (!this.tagData.position) {
              const cDataObj = this.coms[0].tagData.currentData;
              if (cDataObj !== undefined) {
                const tags = cDataObj.tags;
                if (tags !== undefined && tags.length > 0) {
                  const len = tags.length;
                  for (let i = 0; i < len; i++) {
                    const tag = tags[i];
                    this.tabService.getComsDataByStyle(tag.style, callData => {
                      if (callData) {
                        this.coms.push(callData);
                      }
                    }, tag);
                  }
                }
              }
            } else {
              this.hasSearched = false;
            }
          }
        });
      } else {
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, 'middle');
      }
    });
  }

  subChange(obj, indexTab, searchNow?) {
    if (obj !== undefined && obj.partLink !== undefined) {
      this.coms[0].tagData.currentTab = indexTab;
      // 设置各个tab 的 placeholder
      if (this.coms[0].tagData.data[indexTab].partLink.params.placeholder) {
        this.tagData.placeholder = this.coms[0].tagData.data[indexTab].partLink.params.placeholder;
      }
      // 读取各tab 的 搜索历史记录
      if (this.coms[0].tagData.data[indexTab].partLink.params.subSearchType) {

        this.subSearchType = this.coms[0].tagData.data[indexTab].partLink.params.subSearchType;
        this.subSearchHistroy();
      }

      if ((this.tagData.position || this.searchType === "searchType100") && searchNow) {
        if (this.keyword) {
          for (const prop in obj.partLink.params.search) {
            if (obj.partLink.params.search.hasOwnProperty(prop)) {
              if (prop !== 'key') {
                // 参数组合
                obj.partLink.params.search[prop] = this.keyword;
              } else {
                for (const p in obj.partLink.params.search.key) {
                  if (obj.partLink.params.search.key.hasOwnProperty(p)) {
                    obj.partLink.params[p] = obj.partLink.params.search.key[p];
                  }
                }
              }
            }
          }
        } else {
          return;
        }
      } else {
        if (this.tagData.position) {
          this.keyword = "";
          this.hasSearched = false;
          return;
        }
      }
      this.haveResult = true;
      this.httpService.post('application/part',
        {
          viewId: obj.partLink.target,
          sessionId: localStorage.getItem("sessionId"),
          params: obj.partLink.params
        }, (res: any) => {
          console.log(res);
          if (res !== undefined && res != null) {
            this.coms[0].tagData.currentData = JSON.parse(res.script);
            localStorage.setItem("dataMapFixedTabContainer", JSON.stringify(this.coms[0].tagData));
            this.eventService.eventEmit.emit('refreshNav2FixedContainer', 'refreshNav2FixedContainer');
          }
        });
    }
  }
  subSearchHistroy() {
    console.log("search tab type ---->", this.subSearchType);
    this.searchArr = JSON.parse(localStorage.getItem(this.subSearchType))
      ? JSON.parse(localStorage.getItem(this.subSearchType))
      : [];
  }
  clearHistory() {
    this.searchArr = [];

    if (this.subSearchType) {
      localStorage.removeItem(this.subSearchType);
    } else {
      localStorage.removeItem(this.searchType);
    }
  }
  back() {
    this.appGlobalService.goBack();
  }

  onScroll(e: any) {

    e.preventDefault();
  }

  hasSearchResult(event) {
    this.haveResult = event;
  }

  buttonClick(obj) {
    if (obj.type === 'page') {
      const params = {
        pageId: obj.target,
        params: {},
        sessionId: localStorage.getItem('sessionId')
      };
      if (obj.param) {
        params.params = { code: this.titleBar.positionInfo.code };
      }
      this.appGlobalService.goToForward(params);
    } else if (obj.type === 'modal') {
      this.showCityModel(obj.target);
    }
  }

  async showCityModel(target) {
    const that = this;
    const modal = await this.modalController.create({
      component: ChooseCityComponent,
      componentProps: { value: target, entryType: 100, noStorage: true, modalTitle: '选择城市' } // 首页是1 默认不传或者0
    });
    modal.onDidDismiss().then((res) => {
      console.log(JSON.stringify(res));
      if (res && res.data && res.data.i && res.data.n) {
        that.titleBar.position.name = res.data.n;
        that.titleBar.position.code = res.data.i;
        if (this.tagData.link.params && this.tagData.link.params.key) {
          this.tagData.link.params.key.cityId = that.titleBar.position.code;
        } else if (this.tagData.link.params) {
          this.tagData.link.params.key = { cityId: that.titleBar.position.code };
        }
      }

    });
    return await modal.present();
  }

  // 更多
  moreLine(more) {
    const that = this;
    const buttons: any = [];

    more.data.forEach((element, index) => {
      buttons.push(element.label);
    });

    if (more.style !== undefined) {
      // todo 有style的时候显示popover
      this.presentPopover(null, more.data);
    } else {
      // todo 动作菜单
      ActionSheetService.showActionSheetWithOptions(
        {
          options: buttons,
          maskClosable: true
        },
        buttonIndex => {
          if (buttonIndex > -1) {
            console.log(more.data[buttonIndex]);
            ActionSheetService.close();
            setTimeout(() => {
              // that.selectItem(more.data[buttonIndex]);
              that.eventService.eventEmit.emit('searchType100', more.data[buttonIndex]);

            }, 200);
          }
        }
      );
    }
  }


  // 弹窗展示
  popoverClick(ev) {
    const popOverBtn = JSON.parse(localStorage.getItem('popoverBtn'));
    if (popOverBtn) {
      this.presentPopover(ev, popOverBtn);
    }
  }


  async presentPopover(ev: any, data) {
    const popover = await this.popoverController.create({
      component: PopoverComponent,
      cssClass: 'leftAndTop',
      event: ev,
      mode: 'ios',
      animated: true,
      translucent: true,
      componentProps: { tagData: data }
    });
    await popover.present();
    const { role } = await popover.onDidDismiss();
    console.log('onDidDismiss resolved with role', role);
  }

  // 2024.06.27 fixed 修复搜索bug
  ionViewDidEnter() {
    if (!this.hasSearched && this.searchBar) {
      setTimeout(() => {
        this.searchBar.setFocus();
      }, 50);
    }
  }

}
